package com.example.lottery_system.common.interceptor;

import com.example.lottery_system.common.utils.JWTUtil;
import io.jsonwebtoken.Claims;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;


/**
 * 拦截器的实现
 */
@Component
public class LoginInterceptor implements HandlerInterceptor {

    Logger logger = LoggerFactory.getLogger(LoginInterceptor.class);
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {

        String token = request.getHeader("user_token");
        Claims claims = JWTUtil.parseJWT(token);
        logger.info("从拦截器中获取到的token 为 ： " + token);

        if (claims == null) {
//            设置状态码
            logger.error("未登录状态!");
            response.setStatus(401);
            return false;
        }

        return true;
    }
}
